import * as React from "react";
import {Alert, Button, Form, Input} from "element-react";
import {User} from '../data/User';
import {Urls} from "../config/Urls";
import {Http} from "../config/Http";

export class Login extends React.Component<{ login(tokenInfo: any): void }, { user: User, error: { hasError: boolean, errMsg: string } }> {
    constructor(props: any) {
        super(props);
        this.state = {
            user: {
                username: '',
                password: ''
            },
            error: {
                hasError: false,
                errMsg: ''
            }
        };
    }

    onChange(k: string, v: any) {
        this.setState({user: Object.assign({}, this.state.user, {[k]: v})});
    }

    handleSubmit = () => {
        Http.post(Urls.POST_LOGIN, {}, {
            grant_type: 'password',
            username: this.state.user.username,
            password: this.state.user.password,
            client_id: 'coder',
            client_secret: "coderSecret"
        }).then(data => {
            this.setState({
                error: {
                    hasError: false,
                    errMsg: ''
                }
            });
            this.props.login(data);
        }).catch(e => {
            console.error(e);
            this.setState({
                error: {
                    hasError: true,
                    errMsg: '登陆失败'
                }
            })
        })
    };

    errorMsg() {
        if (this.state.error.hasError) {
            return <Alert title={this.state.error.errMsg} type="error"/>;
        }
    }

    render(): React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
        return <Form ref="form" labelWidth="100" model={this.state.user}
                     className="demo-ruleForm">
            {this.errorMsg()}
            <Form.Item label="用户名:" prop="username">
                <Input type="text" value={this.state.user.username}
                       onChange={(e) => this.onChange('username', e)}/>
            </Form.Item>
            <Form.Item label="密码:" prop="password">
                <Input type="password" value={this.state.user.password}
                       onChange={(e) => this.onChange('password', e)}/>
            </Form.Item>
            <Form.Item>
                <Button type="primary" onClick={this.handleSubmit.bind(this)}>提交</Button>
            </Form.Item>
        </Form>;
    }

    componentDidMount(): void {
        document.body.addEventListener('keyup', this.enterFun);
    }

    enterFun = (e: any) => {
        if (e.code === 'Enter') {
            this.handleSubmit();
        }
    };

    componentWillUnmount(): void {
        document.body.removeEventListener('keyup', this.enterFun)
    }
}
